package com.xiaoze.steampy.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoze.steampy.common.dto.LoginDto;
import com.xiaoze.steampy.common.dto.RegisterDto;
import com.xiaoze.steampy.common.lang.Result;
import com.xiaoze.steampy.entity.User;
import com.xiaoze.steampy.service.UserService;
import com.xiaoze.steampy.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 小泽
 * @create 2022-03-28  11:31
 * 记得每天敲代码哦
 */
@RestController
public class AccountController {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;

    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在");
        //SecureUtil.md5(loginDto.getPassword())是对前台的密码进行加密，然后进行比较
        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("密码错误！");
        }

        //账号密码验证成功之后进行最后一次时间修改
        Date date = new Date();
        user.setLastlogintime(date);
        userService.saveOrUpdate(user);

        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 用户可以另一个接口
        return Result.succ(user);
    }
    // 退出

    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }

    /*
    * 注册
    */

    @PostMapping(value = "/register")
    public Result Register(@Validated @RequestBody RegisterDto registerDto){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", registerDto.getUsername()));
         Assert.isNull(user,"用户已存在，请重新注册！");
         Date date = new Date();
         User user1 = new User();

        user1.setUsername(registerDto.getUsername());
       user1.setPassword(SecureUtil.md5(registerDto.getPassword()));
       user1.setEmail(registerDto.getEmail());
       user1.setCreated(date);
       user1.setLastlogintime(date);
       user1.setStatus(0);
       userService.save(user1);
       return Result.succ(null);
    }


}
